﻿public class Solution {
    public string ReverseWords(string s)
    {
        char[] charArr = s.ToCharArray();
        
        // 去除多余空格
        int fast = 0, slow = 0;
        for (; fast < charArr.Length; fast++)
        {
            if (fast == 0 && charArr[fast] == ' ')
            {
                continue;
            }

            if (charArr[fast] == ' ' && charArr[fast] == charArr[fast - 1])
            {
                continue;
            }

            charArr[slow++] = charArr[fast];
        }

        if (charArr[slow - 1] == ' ')
        {
            Array.Resize(ref charArr, slow-1);
        }
        else
        {
            Array.Resize(ref charArr, slow);
        }
        
        // 反转整体字符串
        fast = charArr.Length-1;
        slow = 0;
        for (; slow < fast; slow++, fast--)
        {
            (charArr[slow], charArr[fast]) = (charArr[fast], charArr[slow]);
        }
        
        // 反转单词
        slow = fast = 0;
        int end = 0;
        while (fast < charArr.Length)
        {
            while (fast < charArr.Length && charArr[fast] != ' ')
            {
                fast++;
            }

            if (fast < charArr.Length && charArr[fast] == ' ')
            {
                end = fast - 1;
                for (; slow < end; slow++, end--)
                {
                    (charArr[slow], charArr[end]) = (charArr[end], charArr[slow]);
                }

                slow = ++fast;
            }
            else
            {
                fast--;
                for (; slow < fast; slow++, fast--)
                {
                    (charArr[slow], charArr[fast]) = (charArr[fast], charArr[slow]);
                }
                break;
            }
        }
        return new string(charArr);
    }

    public static void Main(string[] args)
    {
        string s = "the sky is  blue  ";

        Solution solution = new Solution();
        string res = solution.ReverseWords(s);
        Console.WriteLine(res);
    }
}